package com.baibei.ebec.home.index;

import android.content.Context;
import android.os.Handler;
import android.support.annotation.UiThread;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baibei.basic.BasicRecyclerViewAdapter;
import com.baibei.ebec.home.R;
import com.baibei.ebec.home.index.holder.HeadHolder;
import com.baibei.ebec.home.index.holder.HomeHeaderViewHolder;
import com.baibei.ebec.home.index.holder.JewelryHeaderViewHolder;
import com.baibei.ebec.home.index.holder.JewelryTypeViewHolder;
import com.baibei.ebec.home.index.holder.ShipmentProductViewHolder;
import com.baibei.ebec.sdk.BuildConfig;
import com.baibei.model.Area;
import com.baibei.model.BannerInfo;
import com.baibei.model.ProductInfo;
import com.baibei.model.ShipmentInfo;
import com.baibei.module.AreaHelper;
import com.blankj.utilcode.utils.LogUtils;
import com.bumptech.glide.Glide;
import com.rae.swift.Rx;
import com.sunfusheng.marqueeview.MarqueeView;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 首页船列表适配器
 * Created by ChenRui on 2017/8/4 0004 14:11.
 */
public class HomeIndexAdapter extends BasicRecyclerViewAdapter<HomeIndexAdapterModel, RecyclerView.ViewHolder> {

    HomeHeaderViewHolder mHomeHeaderViewHolder;

    private boolean isOnlyShipment;
    private List<BannerInfo> mBannerDataList;
    private int byxj;
    private int byjsj;
    private int hjxj;
    private int hjjsj;
    private Handler handler1;
    private Runnable runnable1;
    private ArrayList<String> news;
    private Handler handler2;
    private Runnable runnable2;

    /**
     * @param isOnlyShipment 是否只显示区域列表
     */
    HomeIndexAdapter(boolean isOnlyShipment) {
        this.isOnlyShipment = isOnlyShipment;
    }

    private JewelryTypeViewHolder.OnAreaListener mAreaListener;
    private ShipmentProductViewHolder.OnProductClickListener mOnProductClickListener;
    private View.OnClickListener mProductItemClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            int position = (int) view.getTag();
            HomeIndexAdapterModel item = getDataItem(position);
            HomeIndexAdapterModel shipment = getDataItem(item.getShipmentIndex());
            mOnProductClickListener.onProductTradeClick(shipment.getShipmentInfo(), item.getProductInfo());
        }
    };

    /**
     * banner点击事件处理
     */
    private OnBannerClickListener mOnBannerClickListener;

    /**
     * banner回调
     *
     * @param OnBannerClickListener OnBannerClickListener
     */
    void setOnBannerClickListener(OnBannerClickListener OnBannerClickListener) {
        mOnBannerClickListener = OnBannerClickListener;
    }

    void setAreaListener(JewelryTypeViewHolder.OnAreaListener areaListener) {
        mAreaListener = areaListener;
    }

    void setOnProductClickListener(ShipmentProductViewHolder.OnProductClickListener onProductClickListener) {
        mOnProductClickListener = onProductClickListener;
    }

    @Override
    public int getItemViewType(int position) {
        HomeIndexAdapterModel item = getDataItem(position);
        if (item == null) {
            return HomeIndexAdapterModel.VIEW_TYPE_SHIPMENT_PRODUCT;
        }
        return item.getViewType();
    }

    @Override
    protected RecyclerView.ViewHolder onCreateViewHolder(LayoutInflater layoutInflater, ViewGroup parent, int viewType) {
        RecyclerView.ViewHolder holder;
        switch (viewType) {
            case HomeIndexAdapterModel.VIEW_TYPE_BANNER:
                // 广告
                if (mHomeHeaderViewHolder == null) {
                    mHomeHeaderViewHolder = new HomeHeaderViewHolder(inflater(R.layout.item_home_header, parent));
                    mHomeHeaderViewHolder.getBanner().setImageLoader(new ImageLoader() {
                        @Override
                        public void displayImage(Context context, Object o, ImageView imageView) {
                            Glide.with(context)
                                    .load(((BannerInfo) o).getPicUrl())
                                    .into(imageView);
                        }
                    });
                    mHomeHeaderViewHolder.getBanner().setDelayTime(4000);
                }
                holder = mHomeHeaderViewHolder;
                break;
            case HomeIndexAdapterModel.VIEW_TYPE_AREA:
                // 比例
                holder = new HeadHolder(inflater(R.layout.layout_head,parent));
                break;
            case HomeIndexAdapterModel.VIEW_TYPE_SHIPMENT_HEADER:
                // 船信息
                holder = new JewelryHeaderViewHolder(inflater(R.layout.item_jewelry_header, parent));
                break;
            default:
                // 商品列表
                holder = new ShipmentProductViewHolder(inflater(R.layout.item_shipment_product, parent));
                break;
        }
        return holder;
    }

    @Override
    protected void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position, HomeIndexAdapterModel item) {
        int viewType = getItemViewType(position);
        switch (viewType) {
            case HomeIndexAdapterModel.VIEW_TYPE_BANNER:
                // 广告 + 地区
                onBindHeaderHolder((HomeHeaderViewHolder) viewHolder, position, item);
                break;
            case HomeIndexAdapterModel.VIEW_TYPE_AREA:
                //显示比例
                onBindPercentHolder((HeadHolder)viewHolder,position,item);
                break;
            case HomeIndexAdapterModel.VIEW_TYPE_SHIPMENT_HEADER:
                // 船信息
                onBindJewelryHeaderHolder((JewelryHeaderViewHolder) viewHolder, position, item);
                break;
            case HomeIndexAdapterModel.VIEW_TYPE_SHIPMENT_PRODUCT:
                // 商品列表
                onBindProductHolder((ShipmentProductViewHolder) viewHolder, position, item);
                break;
        }

    }

    /*
    百分比数据加载
     */
    private void onBindPercentHolder(final HeadHolder viewHolder, int position, HomeIndexAdapterModel item) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                loadPercent();
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                showMarquee();
            }
        }).start();
        handler1 = new Handler();
        runnable1 = new Runnable() {
            @Override
            public void run() {
                viewHolder.tvSilverUp.setText("现价订货"+ byxj +"%");
                viewHolder.tvSilverDown.setText("结算价订货"+ byjsj +"%");
                viewHolder.tvGoldUp.setText("现价订货"+ hjxj +"%");
                viewHolder.tvGoldDown.setText("结算价订货"+ hjjsj +"%");
                viewHolder.tvSilverRed.setLayoutParams(new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT,byxj));
                viewHolder.tvSilverGreen.setLayoutParams(new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT,byjsj));
                viewHolder.tvGoldRed.setLayoutParams(new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT,hjxj));
                viewHolder.tvGoldGreen.setLayoutParams(new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT,hjjsj));
            }
        };
        handler2 = new Handler();
        runnable2 = new Runnable() {
            @Override
            public void run() {
                int[] location = new int[2];
                viewHolder.mv.getLocationOnScreen(location);
                Log.i("top",""+location[1]);
                viewHolder.mv.startWithList(news);
            }
        };
    }

    private void showMarquee() {
//        String url = "http://192.168.1.146:8080/adgox/cbclient/api/banner/SSGB";
        String url = BuildConfig.API_BASE_URL+"cbclient/api/banner/SSGB";
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();
        Call call = client.newCall(request);
        try {
            Response response = call.execute();
            JSONObject json = new JSONObject(response.body().string());
            if (!"SUCCESS".equals(json.optString("code"))){
                return;
            }
            news = new ArrayList<>();
            JSONArray arr = json.optJSONArray("data");
            for (int i = 0 ;i<arr.length() ; i++){
                JSONObject job = new JSONObject(arr.get(i).toString());
                news.add(job.optString("text"));
            }
            handler2.post(runnable2);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void loadPercent() {
//        String url = "http://192.168.1.146:8080/adgox/ordertype/rate";
        String url = BuildConfig.API_BASE_URL+"ordertype/rate";
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();
        Call call = client.newCall(request);
        try {
            Response response = call.execute();
            JSONObject result = new JSONObject(response.body().string());
            JSONObject data = result.optJSONObject("data");

            byxj = data.optInt("BYXJ");
            byjsj = data.optInt("BYJSJ");
            hjxj = data.optInt("HJXJ");
            hjjsj = data.optInt("HJJSJ");

            handler1.post(runnable1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 广告数据加载
     */
    private void onBindHeaderHolder(HomeHeaderViewHolder holder, int position, HomeIndexAdapterModel item) {
        if (Rx.isEmpty(item.getBanners()) || mBannerDataList == item.getBanners()) {
            // 避免同一个刷新频率太快
            return;
        }
        mBannerDataList = item.getBanners();
        holder.getBanner().update(mBannerDataList);
        holder.getBanner().setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int i) {
                if (mOnBannerClickListener != null) {
                    mOnBannerClickListener.onBannerClickListener(mBannerDataList.get(i));
                }
            }
        });
    }

    /**
     * 船信息
     */
    private void onBindJewelryHeaderHolder(JewelryHeaderViewHolder viewHolder, int position, HomeIndexAdapterModel item) {
        final ShipmentInfo info = item.getShipmentInfo();
        Area area = Area.valueOf(info.getArea());
        viewHolder.tvName.setText(info.getName());
        viewHolder.tvName.setCompoundDrawablesWithIntrinsicBounds(AreaHelper.getImageResource(area), 0, 0, 0);
        viewHolder.tvTime.setText(info.getSaleTips());
    }

    /**
     * 商品列表
     */
    private void onBindProductHolder(ShipmentProductViewHolder holder, int position, HomeIndexAdapterModel item) {
        ProductInfo m = item.getProductInfo();
        holder.getTitleView().setText(m.getName());
        holder.getBtn().setTag(position);
        holder.itemView.setTag(position);
        holder.getPriceView().setText(String.format("¥%s", m.getLastPrice() <= 0 ? "暂无" : Rx.formatPrice(m.getLastPrice())));
        holder.getBtn().setOnClickListener(mProductItemClickListener);
        holder.itemView.setOnClickListener(mProductItemClickListener);
        holder.getOrderPrice().setText(""+Rx.formatPrice(m.getPrice())+"元订购");
        Glide.with(holder.itemView.getContext())
                .load(m.getProductPic())
                .into(holder.getProductImageView());

        holder.getNumberView().setText(m.getRepertoryStatus()); //充足与否
    }

    /**
     * 回调
     */
    public interface OnBannerClickListener {

        /**
         * 回调banner点击
         *
         * @param bannerInfo bannerInfo
         */
        void onBannerClickListener(BannerInfo bannerInfo);
    }


}
